package com.zgjkhis.modules.charges.rest;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zgjkhis.domain.PageResult;
import com.zgjkhis.exception.ServiceException;
import com.zgjkhis.logging.aop.log.Log;
import com.zgjkhis.modules.charges.domain.PrescriptionOrder;
import com.zgjkhis.modules.charges.domain.PrescriptionOrderPrint;
import com.zgjkhis.modules.charges.domain.PrescriptionRefund;
import com.zgjkhis.modules.charges.domain.PrescriptionRefundDetail;
import com.zgjkhis.modules.charges.domain.vo.ExpenseDetail;
import com.zgjkhis.modules.charges.domain.vo.ExpenseTotal;
import com.zgjkhis.modules.charges.domain.vo.OrderDetail;
import com.zgjkhis.modules.charges.domain.vo.OrderPrint;
import com.zgjkhis.modules.charges.service.PrescriptionOrderPrintService;
import com.zgjkhis.modules.charges.service.PrescriptionRefundDetailService;
import com.zgjkhis.modules.charges.service.PrescriptionRefundService;
import com.zgjkhis.modules.charges.service.PrescriptionService;
import com.zgjkhis.modules.charges.service.dto.PrescriptionOrderDto;
import com.zgjkhis.modules.charges.service.dto.PrescriptionQueryCriteria;
import com.zgjkhis.modules.charges.service.dto.PrescriptionUpdateCriteria;
import com.zgjkhis.modules.security.security.LoginUserUtil;
import com.zgjkhis.modules.system.domain.*;
import com.zgjkhis.modules.system.service.*;
import com.zgjkhis.modules.util.CharUtil;
import com.zgjkhis.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author yxl 处方订单Controller
 * @Description
 * @Date 2021/7/13 15:40
 **/
@Api(tags = "收费：门诊收费")
@RestController
@RequestMapping("/api/prescription")
public class PrescriptionController {

    @Resource
    private PrescriptionService prescriptionService;

    @Resource
    private ConsultService consultService;

    @Resource
    private InfoService infoService;

    @Resource
    private InfoDrugService infoDrugService;

    @Resource
    private PrescriptionRefundService prescriptionRefundService;

    @Resource
    private OrderAddressService orderAddressService;

    @Resource
    private StoreService storeService;

    @Resource
    private PrescriptionOrderPrintService prescriptionOrderPrintService;

    @Resource
    private DrugService drugService;

    @Resource
    private ApiChannelStoreService apiChannelStoreService;

    @Resource
    private ApiChannelService apiChannelService;

    @Resource
    private PrescriptionRefundDetailService prescriptionRefundDetailService;


    @Log("分页查询处方单")
    @ApiOperation("分页查询处方单")
    @GetMapping(value = "/getPrescriptions")
    public ResponseEntity<PageResult<PrescriptionOrderDto>> getPrescriptions(PrescriptionQueryCriteria criteria, Pageable pageable) {
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        return new ResponseEntity<>(this.prescriptionService.findAllByPageable(criteria, pageable), HttpStatus.OK);
    }

    @Log("查看处方单详情")
    @GetMapping(value = "/detail")
    @ApiOperation("查看处方单详情")
    //    @PreAuthorize("@el.check('supplier:datail')")
    public ResponseEntity<OrderDetail> getDetail(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getId, id).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        Consult consult = consultService.getOne(Wrappers.<Consult>query().lambda().eq(Consult::getConsultNo, order.getConsultNo()));
        //所有处方详情
        List<InfoDrug> infoDrugs = infoDrugService.queryInfoDrugList(order.getOrderNo());//药费
//                infoDrugService.list(Wrappers.<InfoDrug>query().lambda().eq(InfoDrug::getOrderNo,order.getOrderNo()).orderByAsc(InfoDrug::getInfoNo));

        List<ExpenseDetail> list = infoDrugService.queryExpense(order.getOrderNo());
        //所有收费项目

        //费用总计
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal discountPrice = BigDecimal.ZERO;
        BigDecimal refund = BigDecimal.ZERO;
        for (ExpenseDetail expenseDetail : list) {
            total = total.add(expenseDetail.getMoney());
            discountPrice = discountPrice.add(expenseDetail.getDiscountMoney());
            refund = refund.add(expenseDetail.getRefund());
        }
        ExpenseTotal expenseTotal = new ExpenseTotal();
        expenseTotal.setTotal(total);
        expenseTotal.setReceivable(discountPrice);
        expenseTotal.setDisMoney(total.subtract(discountPrice));
        expenseTotal.setPaid(discountPrice);
        expenseTotal.setCash(discountPrice);
        expenseTotal.setRefund(refund);

        //退款原因
        List<PrescriptionRefund> prescriptionRefunds = new ArrayList<>();
        if (order.getPayStatus() == 3 || order.getPayStatus() == 4) {
            prescriptionRefunds = prescriptionRefundService.list(Wrappers.<PrescriptionRefund>query().lambda().eq(PrescriptionRefund::getOrderNo, order.getOrderNo()));
        }
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrder(order);
        orderDetail.setConsult(consult);
        orderDetail.setInfoDrugs(infoDrugs);
        orderDetail.setExpenseDetails(list);
        orderDetail.setExpenseTotal(expenseTotal);
        orderDetail.setRefundList(prescriptionRefunds);
        return new ResponseEntity<>(orderDetail, HttpStatus.OK);
    }


    @Log("打印处方")
    @GetMapping(value = "/printOrder")
    @ApiOperation("打印处方")
    public ResponseEntity<Object> printOrder(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getId, id).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        Consult consult = consultService.getOne(Wrappers.<Consult>query().lambda().eq(Consult::getConsultNo, order.getConsultNo()));
        //所有处方
        List<Info> infos = infoService.list(Wrappers.<Info>query().lambda().eq(Info::getOrderNo, order.getOrderNo()));
        for (Info info : infos) {
            List<InfoDrug> infoDrugs = infoDrugService.list(Wrappers.<InfoDrug>query().lambda().eq(InfoDrug::getInfoNo, info.getInfoNo()));
            for (InfoDrug infoDrug : infoDrugs) {
                infoDrug.setDrugManufactor(drugService.getById(infoDrug.getDrugId()).getDrugManufactor());
            }
            info.setInfoDrugs(infoDrugs);
        }
        OrderAddress orderAddress = orderAddressService.getOne(Wrappers.<OrderAddress>query().lambda().eq(OrderAddress::getOrderNo, order.getOrderNo()));
        Store store = storeService.getById(order.getPharmacyId());

        OrderPrint orderDetail = new OrderPrint();

        if (order.getOrderType() == 2) {
            ApiChannel apichannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getAppId, order.getSourceId()));
            ApiChannelStore apiChannelStore = apiChannelStoreService.getOne(Wrappers.<ApiChannelStore>query().lambda()
                    .eq(ApiChannelStore::getPharmacyId, order.getSourceStoreId())
                    .eq(ApiChannelStore::getHisStoreId, order.getPharmacyId())
                    .eq(ApiChannelStore::getChannelId, apichannel.getId())
            );
            orderDetail.setApiChannelStore(apiChannelStore);
        }
        orderDetail.setRefund(BigDecimal.ZERO);
        if (order.getPayStatus() == 3 || order.getPayStatus() == 4) {
            //退款原因
            List<PrescriptionRefundDetail> prescriptionRefunds = new ArrayList<>();
            if (order.getPayStatus() == 3 || order.getPayStatus() == 4) {
                prescriptionRefunds = prescriptionRefundDetailService.list(Wrappers.<PrescriptionRefundDetail>query().lambda().eq(PrescriptionRefundDetail::getOrderNo, order.getOrderNo()));
                BigDecimal reduce = prescriptionRefunds.stream().map(PrescriptionRefundDetail::getRefund).reduce(BigDecimal.ZERO, BigDecimal::add);
                orderDetail.setRefund(reduce);
            }
            orderDetail.setPrescriptionRefunds(prescriptionRefunds);
        }
        //添加处方打印
        orderDetail.setOrder(order);
        orderDetail.setConsult(consult);
        orderDetail.setInfos(infos);
        orderDetail.setOrderAddress(orderAddress);
        orderDetail.setStore(store);


//        //保存打印记录
//        PrescriptionOrderPrint prescriptionOrderPrint=new PrescriptionOrderPrint();
//        prescriptionOrderPrint.setOrderNo(order.getOrderNo());
//        prescriptionOrderPrint.setCreateUser(SecurityUtils.getUserId().toString());
//        prescriptionOrderPrintService.save(prescriptionOrderPrint);

        return new ResponseEntity<>(orderDetail, HttpStatus.OK);
    }

    @Log("打印处方")
    @GetMapping(value = "/printCount")
    @ApiOperation("打印处方")
    public ResponseEntity<Object> printCount(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getId, id).eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }

        //保存打印记录
        PrescriptionOrderPrint prescriptionOrderPrint = new PrescriptionOrderPrint();
        prescriptionOrderPrint.setOrderNo(order.getOrderNo());
        prescriptionOrderPrint.setCreateUser(SecurityUtils.getUserId().toString());
        prescriptionOrderPrintService.save(prescriptionOrderPrint);

        return new ResponseEntity<>(true, HttpStatus.OK);
    }

//    @Log("调剂")
//    @ApiOperation("调剂")
//    @PostMapping(value = "/confirmOrder")
////    @PreAuthorize("@el.check('supplier:edit')")
//    public ResponseEntity<Object> confirmOrder(String id) {
//        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getId, id).eq(PrescriptionOrder::getPharmacyId,LoginUserUtil.getPharmId()));
//        if(CharUtil.isEmpty(id)){
//            throw new ServiceException("id不能为null");
//        }
//
//        if(CharUtil.isEmpty(order)){
//            throw new ServiceException("查无此订单");
//        }
//        if(order.getOrderCondition()!=2){
//            throw new ServiceException("非调剂中的订单不能调剂");
//        }
//        prescriptionService.confirmOrder(order);
//        return ResponseEntity.ok(true);
//    }
//
//    @Log("订单退款")
//    @ApiOperation("订单退款")
//    @PostMapping(value = "/refund")
////    @PreAuthorize("@el.check('supplier:edit')")
//    public ResponseEntity<Object> refund(String orderNo,String refundMsg,@Validated @RequestBody ValidList<PrescriptionRefundCriteria> prescriptionRefundCriteria){
//        if(CharUtil.isEmpty(orderNo)){
//            throw new ServiceException("订单号不能为空");
//        }
//        prescriptionService.refund(prescriptionRefundCriteria,refundMsg,orderNo);
//        return ResponseEntity.ok(true);
//    }

    @Log("订单修改寄送方式")
    @ApiOperation("订单修改寄送方式")
    @PostMapping(value = "/changeSend")
//    @PreAuthorize("@el.check('supplier:edit')")
    public ResponseEntity<Object> changeSend(@RequestBody BigDecimal expressFee, @Validated @RequestBody OrderAddress orderAddress) {
        if (CharUtil.isEmpty(orderAddress.getOrderNo())) {
            throw new ServiceException("订单号不能为空");
        }
        if (expressFee == null) {
            throw new ServiceException("邮寄费不能为空");
        }
        orderAddress.setPharmacyId(LoginUserUtil.getPharmId());
        PrescriptionOrder order = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderStatus, 0).eq(PrescriptionOrder::getOrderNo, orderAddress.getOrderNo()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("订单不存在");
        }
        orderAddressService.save(orderAddress);
        PrescriptionOrder temp = new PrescriptionOrder();
        temp.setExpressFee(expressFee);
        temp.setDeliveryType(1);
        temp.setTotalFee(order.getTotalFee().add(expressFee));
        temp.setId(order.getId());
        prescriptionService.updateById(temp);
        return ResponseEntity.ok(true);
    }

    @Log("修改订单状态")
    @ApiOperation("修改订单状态")
    @PostMapping(value = "/checkOrder")
    public ResponseEntity<Object> checkOrder(@Validated @RequestBody PrescriptionUpdateCriteria order) {
        PrescriptionOrder prescriptionOrder = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getPharmacyId, LoginUserUtil.getPharmId()).eq(PrescriptionOrder::getOrderStatus, 0).eq(PrescriptionOrder::getOrderNo, order.getOrderNo()));
        if (CharUtil.isEmpty(prescriptionOrder)) {
            throw new ServiceException("订单不存在");
        }
        PrescriptionOrder tempOrder = new PrescriptionOrder();
        tempOrder.setId(prescriptionOrder.getId());
//        tempOrder.setPayStatus(order.getPayStatus());
        tempOrder.setOrderCondition(order.getOrderCondition());
        //审核通过
        if (order.getOrderCondition().equals("2")) {
            tempOrder.setOrderCondition(2);
            tempOrder.setCheckUserId(SecurityUtils.getUserId().toString());
            tempOrder.setCheckUser(LoginUserUtil.getNickName());
            tempOrder.setCheckTime(new Date());
        }
        prescriptionService.updateById(tempOrder);
        return ResponseEntity.ok(true);
    }

}
